package com.wfb.controller;

import com.wfb.bean.ImgContext;
import com.wfb.service.ImgContextService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class ImgUploadController {
    @Autowired
    private ImgContextService imgContextService;

    /**
     * 下载图片
     *
     * @param id
     * @return
     */
    @RequestMapping("download")
    public ResponseEntity<byte[]> download(int id, HttpServletRequest request) throws IOException {
        String rootFile = new File(request.getServletContext().getRealPath("/")).getParentFile().getPath();
        String icon = imgContextService.findIconByid(id);
        String fileName = icon.substring(icon.lastIndexOf("/") + 1);
        System.out.println("被下载文件名：" + fileName);
        //获取到文件
        File file = new File(rootFile, icon);
        HttpHeaders headers = new HttpHeaders();
        // 下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(fileName.getBytes("UTF-8"),
                "iso-8859-1");
        // 通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        // application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

    /**
     * 查询图片列表
     *
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list() {
        ModelAndView view = new ModelAndView("list.jsp");
        view.addObject("list", imgContextService.find());
        return view;
    }

    @RequestMapping("remove")
    public ModelAndView remove(int id, HttpServletRequest request) {
        String rootFile = new File(request.getServletContext().getRealPath("/")).getParentFile().getPath();
        ModelAndView view = new ModelAndView("redirect:list");
        String icon = imgContextService.findIconByid(id);
        //获取到文件
        File imgFile = new File(rootFile, icon);
        boolean b = false;
        System.out.println("本地文件名：" + imgFile.getName());
        System.out.println("数据库文件名：" + icon.substring(icon.lastIndexOf("/") + 1));
        if (imgFile.isFile() && imgFile.getName().equals(icon.substring(icon.lastIndexOf("/") + 1))) {
            b = imgFile.delete();
        }
        System.out.println("文件删除成功");
        if (!b) {
            System.out.println("文件删除错误");
            view.addObject("error", "文件删除失败");
            view.setViewName("error.jsp");
            return view;
        }
        //删除数据库
        int i = imgContextService.remove(id);
        if (i == 0) {
            System.out.println("数据库删除错误");
            view.addObject("error", "删除失败");
            view.setViewName("error.jsp");
        }
        return view;
    }

    /***
     * 文件上传
     * @return
     */
    @RequestMapping("upload")
    public ModelAndView upload(HttpServletRequest request, ImgContext imgContext, MultipartFile file) {
        ModelAndView view = new ModelAndView("redirect:list");
        //图片储存位置
        String dir = "/img/";
        //获取文件上传路径(先获取当前项目路径之后获取父级路径在拼接图片路径)
        String upLooad = new File(request.getServletContext().getRealPath("/")).getParentFile().getPath() + dir;
        System.out.println("上传路径：" + upLooad);
        //获取文件后缀名
        String fileName = file.getOriginalFilename();
        String type = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println("文件类型：" + type);
        //判断文件类型
        if (!(type.equals("png") || type.equals("jpg"))) {
            //不是图片报错
            System.out.println("文件类型错误！仅支持jsp和png格式");
            view.addObject("error", "文件类型错误！仅支持jsp和png格式");
            view.setViewName("error.jsp");
            return view;
        }
        //使用uuid生成一个新文件名
        String newName = UUID.randomUUID().toString().replace("-", "") + "." + type;
        System.out.println("新文件名：" + newName);
        try {
            file.transferTo(new File(upLooad, newName));
        } catch (IOException e) {
            System.out.println("上传失败msg:" + e.getMessage());
            view.addObject("error", "上传失败msg:" + e.getMessage());
            view.setViewName("error.jsp");
            return view;
        }
        //储存路径
        String iconUrl = dir + newName;
        System.out.println("图片访问路径：" + iconUrl);
        imgContext.setIcon(iconUrl);
        imgContext.setUploadTime(new SimpleDateFormat("yyyy-MM-dd hh:ss:mm").format(new Date()));
        int i = imgContextService.add(imgContext);
        if (i == 0) {
            System.out.println("上传失败msg：数据库储存失败");
            view.addObject("error", "上传失败msg：数据库储存失败");
            view.setViewName("error.jsp");
        }
        return view;
    }

}
